package week02

// 874. 模拟行走机器人
// https://leetcode-cn.com/problems/walking-robot-simulation/

func robotSim(commands []int, obstacles [][]int) int {
	var block = make(map[int]struct{})
	for _, obstacle := range obstacles {
		block[hash(obstacle[0], obstacle[1])] = struct{}{}
	}

	var x, y = 0, 0
	var ans = 0
	var dx = []int{0, 1, 0, -1}
	var dy = []int{1, 0, -1, 0}
	var dir = 0
	for _, cmd := range commands {
		if cmd >= 1 && cmd <= 9 {
			// 移动
			for i := 0; i < cmd; i++ {
				nextX, nextY := x + dx[dir], y + dy[dir]
				if _, ok := block[hash(nextX, nextY)]; ok {
					break
				}
				x, y = nextX, nextY
				ans = max(ans, x * x + y * y)
			}
		} else if cmd == -1 {
			// 右转
			dir = (dir + 1) % 4
		} else if cmd == -2 {
			// 左转
			dir = (dir - 1 + 4) % 4
		}
	}
	return ans
}

// -30000  +30000
func hash(x, y int) int {
	return x * 60001 + y
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}